package com.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.project.bean.SellCarBean;
import com.project.bean.UserBean;
import com.project.mapper.ISellCarMapper;
import com.project.service.ISellCarService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class SellCarServiceImpl implements ISellCarService {
    @Autowired
    private ISellCarMapper sellCarMapper;

    /**
     * 按登陆用户id查询销售车集合
     *
     * @param userId 登陆用户编号
     * @return 销售车集合
     */
    @Override
    public List<SellCarBean> findByUserId(Integer userId) {
        return sellCarMapper.findUserId(userId);
    }

    /**
     * 添加销售商品
     * 通过商品编号查询是否已存在销售车记录则数量加一
     * 如果销售车不存在该商品则添加该商品并默认数量为1
     *
     * @param number 商品编号
     * @param userId 登陆用户编号
     */
    @Override
    public void add(String number, Integer userId) {
        QueryWrapper<SellCarBean> qw = new QueryWrapper<>();
        qw.eq("fk_productId", number);
        qw.eq("fk_userId", userId);
        SellCarBean sellCar = sellCarMapper.selectOne(qw);
        if (sellCar == null) {
            sellCar = new SellCarBean(number, userId);
            sellCarMapper.insert(sellCar);
        } else {
            sellCar.setNum(sellCar.getNum() + 1);
            sellCarMapper.updateById(sellCar);
        }
    }

    /**
     * 移除销售商品
     *
     * @param sellCarId 销售车编号
     */
    @Override
    public void del(Integer sellCarId) {
        sellCarMapper.deleteById(sellCarId);
    }

    /**
     * 修改销售数量
     *
     * @param sellCarId 销售车编号
     * @param num       销售数量
     */
    @Override
    public void update(Integer sellCarId, Integer num) {
        SellCarBean sellCar = new SellCarBean();
        sellCar.setId(sellCarId);
        sellCar.setNum(num);
        sellCarMapper.updateById(sellCar);
    }

    /**
     * 计算销售车的总价
     *
     * @param userId 用户编号
     * @return 订单总金额
     */
    @Override
    public Integer getTotalPrice(Integer userId) {
        return sellCarMapper.getSellMoney(userId);
    }
}
